#!/usr/bin/env python
# -*- coding: utf-8 -*-
gw_libs_detected = False
from gettext import gettext as _

try:
	from imaplib import *
	from ical import *
#	import atom
#	import getopt
	import time
	gw_libs_detected = True
except Exception,e:
	print _("Not all dependencies for Groupwise are met.")
	print _("python-vobject (0.5) is required.")
	print e

##
## Groupwise via IMAP Class
##

class GroupwiseCalendar(iCalCalendar):
	capabilities = ['provider']
	def __init__(self):
		iCalCalendar.__init__(self)
		self.Plugin_Name = "Groupwise"
		self.Plugin_Author = "Florian Dorn"	
		self.Plugin_Website = ""	
		#set the capability to provider
		
		self.options['username'] 		= ''
		self.options['password'] 		= ''
		self.options['server']			= ''
		self.options['ssl'] 				= True
		self.options['color'] 			= '#436B9E'
		self.options['timezoneadjust'] 	= 0
		self.options['folder'] 			= 'Calendar'
		self.options['port_ssl'] 		= 993
		self.options['port_normal'] 		= 143		
	def initPlugin(self, options):
		CalendarProviderBase.initPlugin(self,options)
		self.timezoneadjust = self.options['timezoneadjust']
		self.server_url = self.options['server']
		self.ssl = bool(self.options['ssl'])
		if(self.ssl):
			self.server_port = int(self.options['port_ssl'])
		else:
			self.server_port = int(self.options['port_normal'])
		self.user = self.options['username']
		self.password = self.options['password']
		self.folder = self.options['folder']
		self.urls = ['imap://%s@%s:%s/%s' %(self.user,self.server_url,self.server_port,self.folder )]

		pass
	def getAllEvents(self,start_date=None,end_date=None):
		if(not ical_lib_detected):
			self.notifyError(_("The python iCal library is not installed"))
			return 
		#connect to the server
		try:
			if(self.ssl):
				self.server = IMAP4_SSL(self.server_url,self.server_port)
			else:
				self.server = IMAP4(self.server_url,self.server_port)				
			self.server.login(self.user, self.password)
		except Exception,e:
			self.notifyError(_("Could not establish connection the server."))
			self.notifyError(_("Please check the Groupwise settings"))
			self.update_ok = False
			print e
			return self.update_ok
		try:
			self.calendarDir = self.server.select(self.folder)
		except Exception,e:
			self.notifyError(_("Could not Open folder <i>%s</i>") % self.folder)
			self.update_ok = False
			print e	
			return self.update_ok	
		orig_url = self.urls[0]
		#print self.calendarDir
		#TODO: add support for multiple calendars (they are subfolders of the base calendar folder)
		cal_str = ""
		try:
			typ, data = self.server.search(None, '(UNDELETED)')
		except Exception,e:
			self.notifyError(_("Could not read the Calendar Folder <i>%s</i>") % self.folder)
			print e
			return
		uids = data[0].split()
		header_written = False
		self.msg_cache = {}
		if (len(uids) > 0):
			i = 0
			for uid in uids:
					vcal = ""
					if (self.msg_cache.has_key(uid)):
						self.url = orig_url +'/'+ str(uid)
					else:
						typ, msg_data = self.server.fetch(uid, '(BODY[TEXT])')
						
						vcal = msg_data[0][1][msg_data[0][1].rfind('BEGIN:VCALENDAR'):msg_data[0][1].rfind('END:VCALENDAR')+len('END:VCALENDAR')]
						self.msg_cache[uid] = vcal
					if(len(vcal)>0):
						i+=1
						self.getEventsFromString(vcal,orig_url,self.options['color'])
			if(i==0):
				self.notifyError(_("No appointments were found in <i>%s</i>") % self.folder)
		self.server.logout()
		self.update_ok = True
		return self.update_ok
	##
	## retrieve the Event from a VCALENDAR
	##
	def getEventFromVcal(self,string,marker_start,marker_end):
		start_pos = string.rfind(marker_start)+len(marker_start)
		end_pos = string.rfind(marker_end)
		return string[0:start_pos] + string[start_pos:end_pos].replace("\r\n"," ") + string[end_pos:]
	def dumpCache(self):
		try:
			f=open("groupwise.cache.cPickle", 'w')
			#p.dump(self.msg_cache,f)
			f.close()
		except:
			print "Could not dump the cache"
	def loadCache(self):
		try:
			f=open("groupwise.cache.cPickle", 'r')
			self.msg_cache = p.load(f)
			f.close()
		except:
			print "readSettings error"
	def getSettingsPanel(self):
		"""return a gtk Widget showind the settings"""
		return gtk.Label(_("No configuration needed"))
	def applySettings(self):
		"""apply the changes to self.options made to the widgets"""			
